<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/3/5
 * Time: 16:05
 */

namespace app\controllers;

use app\models\Node;
use app\models\RemarkForm;
use app\models\User;
use Yii;
use app\models\Project;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\NotFoundHttpException;

class ProjectController extends BaseController
{
    /**
     * 项目管理列表
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            //筛选条件
            $where = ['and'];
            $name = Yii::$app->request->get('name');
            if ($name){
                $where[] = ['=','name',$name];
            }
            $phone = Yii::$app->request->get('phone');
            if ($phone){
                $where[] = ['or',['=','phone',$phone],['=','other_phone',$phone]];
            }
            $node_id = Yii::$app->request->get('node_id');
            if ($node_id){
                $where[] = ['=','node_id',$node_id];
            }
            $created_user_id = Yii::$app->request->get('created_user_id');
            if ($created_user_id){
                $where[] = ['=','created_user_id',$created_user_id];
            }
            $follow_at_start = Yii::$app->request->get('follow_at_start');
            $follow_at_end = Yii::$app->request->get('follow_at_end');
            if ($follow_at_start && !$follow_at_end){
                $where[] = ['>=','follow_at',strtotime($follow_at_start)];
            }elseif (!$follow_at_start && $follow_at_end){
                $where[] = ['<=','follow_at',strtotime($follow_at_end)];
            }elseif ($follow_at_start && $follow_at_end){
                $where[] = ['between','follow_at',strtotime($follow_at_start),strtotime($follow_at_end)];
            }
            $next_follow_at_start = Yii::$app->request->get('next_follow_at_start');
            $next_follow_at_end = Yii::$app->request->get('next_follow_at_end');
            if ($next_follow_at_start && !$next_follow_at_end){
                $where[] = ['>=','next_follow_at',strtotime($next_follow_at_start)];
            }elseif (!$next_follow_at_start && $next_follow_at_end){
                $where[] = ['<=','next_follow_at',strtotime($next_follow_at_end)];
            }elseif ($next_follow_at_start && $next_follow_at_end){
                $where[] = ['between','next_follow_at',strtotime($next_follow_at_start),strtotime($next_follow_at_end)];
            }
            $created_at_start = Yii::$app->request->get('created_at_start');
            $created_at_end = Yii::$app->request->get('created_at_end');
            if ($created_at_start && !$created_at_end){
                $where[] = ['>=','created_at',strtotime($created_at_start)];
            }elseif (!$created_at_start && $created_at_end){
                $where[] = ['<=','created_at',strtotime($created_at_end)];
            }elseif ($created_at_start && $created_at_end){
                $where[] = ['between','created_at',strtotime($created_at_start),strtotime($created_at_end)];
            }

            $query = Project::find()->with(['node','user'])->where($where)->orderBy('id desc');
            $count = $query->count();

            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->asArray()->all();
            foreach ($data as &$d){
                $d['show_url'] = Url::to(['show','id'=>$d['id']]);
                $d['edit_url'] = Url::to(['edit','id'=>$d['id']]);
                $d['node_url'] = Url::to(['node','id'=>$d['id']]);
                $d['remark_url'] = Url::to(['remark','id'=>$d['id']]);
                $d['destroy_url'] = Url::to(['destroy','id'=>$d['id']]);
                $d['sex_text'] = Project::$sex_info[$d['sex']];
                $d['follow_at'] = $d['follow_at']?date('Y-m-d H:i',$d['follow_at']):'-';
                $d['next_follow_at'] = $d['next_follow_at']?date('Y-m-d H:i',$d['next_follow_at']):'-';
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['node_name'] = $d['node']['name'];
                $d['created_user_name'] = $d['user']['username'];
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        $nodes = Node::find()->orderBy('sort asc')->addOrderBy('id asc')->asArray()->all();
        $users = User::find()->all();
        return $this->render('index',['nodes'=>$nodes,'users'=>$users]);
    }

    /**
     * 添加项目
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Project();
        $nodes = Node::find()->orderBy('sort asc')->addOrderBy('id asc')->asArray()->all();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'create';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','添加成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('create',['model'=>$model,'nodes'=>$nodes]);
    }

    /**
     * 编辑项目
     * @param $id
     * @return string|\yii\web\Response
     */
    public function actionEdit($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        $nodes = Node::find()->orderBy('sort asc')->addOrderBy('id asc')->asArray()->all();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'edit';
            if ($model->load($data,'')&&$model->save()){
                Yii::$app->session->setFlash('info','更新成功');
                return $this->redirect(['index']);
            }
        }
        return $this->render('edit',['model'=>$model,'nodes'=>$nodes]);
    }

    /**
     * 项目详情
     * @param $id
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionShow($id)
    {
        $model = Project::find()->with('node')->where(['id'=>$id])->one();
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        $follow = (new Query())->from('project_remark as r')
            ->leftJoin('user as u','r.user_id=u.id')
            ->select(['u.username','r.content','r.created_at as follow_at','r.next_follow_at'])
            ->where(['r.project_id'=>$id])
            ->orderBy('r.id desc')
            ->one();
        return $this->render('show',['model'=>$model,'follow'=>$follow]);
    }

    /**
     * 项目备注
     * @param $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionRemark($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        $form = new RemarkForm();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if ($form->load($data,'')&&$form->save()){
                Yii::$app->session->setFlash('info','添加备注成功');
                return $this->redirect(['show','id'=>$id]);
            }
        }
        return $this->render('remark',['model'=>$model,'form'=>$form]);
    }

    /**
     * 项目节点更新
     * @param $id
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionNode($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            throw new NotFoundHttpException('项目不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'node';
            if ($model->load($data,'')&&$model->updateNode()){
                Yii::$app->session->setFlash('info','更新节点成功');
                return $this->redirect(['show','id'=>$id]);
            }
        }
        $nodes = Node::find()->orderBy('sort asc')->addOrderBy('id asc')->asArray()->all();
        return $this->render('node',['model'=>$model,'nodes'=>$nodes]);
    }

    /**
     * 删除项目
     * @param $id
     * @return \yii\web\Response
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDestroy($id)
    {
        $model = Project::findOne($id);
        if ($model===null){
            return $this->asJson(['code'=>1,'msg'=>'项目不存在']);
        }
        if ($model->delete()){
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }
        return $this->asJson(['code'=>0,'msg'=>'删除失败']);
    }

    /**
     * 项目节点进度
     * @param $id
     * @return \yii\web\Response
     */
    public function actionNodeList($id)
    {
        if (Yii::$app->request->isAjax){
            $query = (new Query())->from('project_node as n')
            ->leftJoin('user as u','n.user_id=u.id')
            ->select(['n.old','n.new','n.content','n.created_at','u.username'])
            ->where(['n.project_id'=>$id])
            ->orderBy('n.id desc');
            $count = $query->count();
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->all();
            $nodes = Node::find()->select(['name','id'])->indexBy('id')->column();
            foreach ($data as &$d){
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['old'] = ArrayHelper::getValue($nodes,$d['old']);
                $d['new'] = ArrayHelper::getValue($nodes,$d['new']);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
    }

    /**
     * 项目备注进度
     * @param $id
     * @return \yii\web\Response
     */
    public function actionRemarkList($id)
    {
        if (Yii::$app->request->isAjax){
            $query = (new Query())->from('project_remark as r')
                ->leftJoin('user as u','r.user_id=u.id')
                ->select(['r.content','r.next_follow_at','r.created_at','u.username'])
                ->where(['r.project_id'=>$id])
                ->orderBy('r.id desc');
            $count = $query->count();
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $query->offset(($page-1)*$limit)->limit($limit)->all();
            foreach ($data as &$d){
                $d['created_at'] = $d['created_at']?date('Y-m-d H:i',$d['created_at']):'-';
                $d['next_follow_at'] = $d['next_follow_at']?date('Y-m-d H:i',$d['next_follow_at']):'-';
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
    }

    /**
     * 项目概要
     * @return string|\yii\web\Response
     */
    public function actionCount()
    {
        if (Yii::$app->request->isAjax){
            $data = [];
            $nodes = Node::find()->orderBy('sort asc')
                ->addOrderBy('id asc')
                ->with('project')
                ->all();
            foreach ($nodes as $node){
                $data[$node['name']] = count($node['project']);
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'data' => $data,
            ]);
        }
        $day_start = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $day_end = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
        $projects = Project::find()->where(['between','next_follow_at',$day_start,$day_end])
            ->orderBy('next_follow_at asc')
            ->limit(9)
            ->all();
        foreach ($projects as &$p){
            $p['follow_at'] = $p['follow_at']?date('Y-m-d H:i',$p['follow_at']):'-';
        }
        return $this->render('count',['projects'=>$projects]);
    }

}